package com.cratos.xxgram.platf.group;

import com.cratos.xxgram.platf.base.BaseService;
import com.cratos.xxgram.platf.base.RetCodes;
import com.cratos.xxgram.platf.base.UserInfo;
import static com.cratos.xxgram.platf.rongcloud.NotifyContent.GroupNotificationMessage;
import static com.cratos.xxgram.platf.rongcloud.NotifyContent.GroupNotificationMessage.QuitGroup;
import static com.cratos.xxgram.platf.rongcloud.NotifyContent.GroupNotificationMessage.CreateGroup;
import static com.cratos.xxgram.platf.rongcloud.NotifyContent.GroupNotificationMessage.DissMissGroup;
import static com.cratos.xxgram.platf.rongcloud.NotifyContent.GroupNotificationMessage.KickedGroup;
import com.cratos.xxgram.platf.rongcloud.RongCloudMessage;
import static com.cratos.xxgram.platf.rongcloud.RongCloudMessage.RongCloudGroupMessage;
import com.cratos.xxgram.platf.rongcloud.RongCloudService;
import java.util.*;
import javax.annotation.Resource;
import org.redkale.net.http.RestMapping;
import org.redkale.service.RetResult;
import org.redkale.source.FilterExpress;
import org.redkale.source.FilterFunc;
import org.redkale.source.FilterNode;
import org.redkale.util.Sheet;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.redkale.boot.Application;
import org.redkale.util.Comment;

/**
 *
 * @author SquRab
 */
//@RestService(name = "group", comment = "群组服务")
public class GroupService extends BaseService {

    @Resource
    private RongCloudService rongCloudService;

    @RestMapping(name = "createGroup", auth = true, comment = "创建修改群组")
    public RetResult createGroup(UserInfo userInfo, GroupDetail bean, final int[] userIds) {
        int userId = userInfo.getUserid();

        // 群名称不能为空
        if ("".equals(bean.getGroupname())
                || null == bean.getGroupname()) {
            return RetCodes.retResult(RetCodes.RET_GROUP_NAME_EMPTY);
        }
        int groupid = source.getNumberResult(GroupDetail.class, FilterFunc.MAX, 1_0000_0000, "groupid", (FilterNode) null).intValue() + 1;
        bean.setGroupid(groupid);
        bean.setCreatetime(System.currentTimeMillis());
        bean.setCreateuserid(userId);
        // 异步回调融云平台
        RetResult result = rongCloudService.createGroup(userId, bean.getGroupid(), bean.getGroupname()).whenComplete((o, t) -> {
            if (o.isSuccess()) {
                source.insert(bean);//保存群信息
                join(userInfo, bean); //群主加群
                for (int id : userIds) {
                    UserInfo user = source.find(UserInfo.class, id);
                    if (user == null) {
                        logger.finest("user is null " + id);
                        continue;
                    }
                    join(user, bean);
                }
                //更新群人数
                refreshGroupUserNum(bean.getGroupid());
                //先拉群再发通知
                CreateGroup createGroupMsg = new CreateGroup();
                createGroupMsg.setOperatorNickname(userInfo.getUsername());
                createGroupMsg.setTargetGroupName(bean.getGroupname());
                publishGroupNotifyMessage(RongCloudGroupMessage.SUB_MSG_DEFAULT, groupid, userId, GroupNotificationMessage.OP_CREATE, createGroupMsg,
                        String.format(GroupNotificationMessage.OP_CREATE_MSG, userInfo.getUsername()));
            }
        }).join();
        logger.info("create group message " + result.toString());
        if (!result.isSuccess()) {
            return result;
        }
        return RetResult.success(bean);
    }

    @Comment("创建修改群组")
    public RetResult createGroupWs(int currentUserId, GroupDetail bean, final int[] userIds) {
        // 群名称不能为空
        if ("".equals(bean.getGroupname())
                || null == bean.getGroupname()) {
            return RetCodes.retResult(RetCodes.RET_GROUP_NAME_EMPTY);
        }
        int groupid = source.getNumberResult(GroupDetail.class, FilterFunc.MAX, 1_0000_0000, "groupid", (FilterNode) null).intValue() + 1;
        bean.setGroupid(groupid);
        bean.setCreatetime(System.currentTimeMillis());
        bean.setCreateuserid(currentUserId);
        source.insert(bean);//保存群信息
        UserInfo userInfo = source.find(UserInfo.class, currentUserId);
        joinWs(userInfo.getUserid(), userInfo.getUsername(), bean); //群主加群
        for (int id : userIds) {
            UserInfo user = source.find(UserInfo.class, id);
            if (user == null) {
                logger.finest("user is null " + id);
                continue;
            }
            joinWs(user.getUserid(), user.getUsername(), bean);
        }
        //更新群人数
        refreshGroupUserNum(bean.getGroupid());
        return RetResult.success(bean);
    }

    /**
     * @param groupId 群组ID
     * @param optionUserId 操作人ID
     * @param operationType 操作类型
     * @param opetion 操作详情数据
     * @param message 消息
     * @return
     */
    @Comment("群通知消息")
    private void publishGroupNotifyMessage(int msgSubType, int groupId, int optionUserId, String operationType, GroupNotificationMessage.OpetionGroup opetion, String message) {
        GroupNotificationMessage groupNotificationMessage = new GroupNotificationMessage(Integer.toString(optionUserId, 36), operationType, opetion, message);
        int toUserId = 0;
        RongCloudGroupMessage groupMessage = new RongCloudGroupMessage(msgSubType, groupId, 0, optionUserId, toUserId, GroupNotificationMessage.TYPE, groupNotificationMessage);
        groupMessage.setType(RongCloudMessage.GROUP);
        //发布下消息
        rongCloudService.pubMessage(groupMessage);
    }

    @RestMapping(name = "updateGroupNotice", auth = true, comment = "修改群组公告")
    public RetResult updateGroupNotice(UserInfo userInfo, GroupDetail bean) {
        GroupDetail detail = source.find(GroupDetail.class, FilterNode
                .create("groupid", FilterExpress.EQUAL, bean.getGroupid())
                .and("createuserid", FilterExpress.EQUAL, userInfo.getUserid()));
        if (detail != null) {
            source.updateColumn(GroupDetail.class, bean.getGroupid(), "groupnotice", bean.getGroupnotice());
        } else {
            return RetCodes.retResult(RetCodes.RET_RONGCLOUD_UPDATE_GROUP_ERROR);
        }
        //先更新在发通知
        GroupNotificationMessage.UpdateGroupDetail updateGroupMsg = new GroupNotificationMessage.UpdateGroupDetail();
        updateGroupMsg.setOperatorNickname(userInfo.getUsername());
        updateGroupMsg.setTargetGroupName(bean.getGroupname());
        // 发布更新群信息消息
        publishGroupNotifyMessage(RongCloudGroupMessage.SUB_MSG_DEFAULT, bean.getGroupid(),
                userInfo.getUserid(), GroupNotificationMessage.OP_UPDATE, updateGroupMsg, String.format(GroupNotificationMessage.OP_UPDATE_MSG, userInfo.getUsername()));
        return RetResult.success();
    }

    @Comment("跟新通知")
    public RetResult updateGroupNoticeWs(int currentUserid, GroupDetail bean) {
        GroupDetail detail = source.find(GroupDetail.class, FilterNode
                .create("groupid", FilterExpress.EQUAL, bean.getGroupid())
                .and("createuserid", FilterExpress.EQUAL, currentUserid));
        if (detail != null) {
            source.updateColumn(GroupDetail.class, bean.getGroupid(), "groupnotice", bean.getGroupnotice());
        } else {
            return RetCodes.retResult(RetCodes.RET_RONGCLOUD_UPDATE_GROUP_ERROR);
        }
        return RetResult.success();
    }

    @Comment("更新群名称")
    public RetResult updateGroupNameWs(int currentUserid, GroupDetail bean) {
        GroupDetail detail = source.find(GroupDetail.class, FilterNode
                .create("groupid", FilterExpress.EQUAL, bean.getGroupid())
                .and("createuserid", FilterExpress.EQUAL, currentUserid));
        if (detail != null) {
            source.updateColumn(GroupDetail.class, bean.getGroupid(), "groupname", bean.getGroupname());
        } else {
            return RetCodes.retResult(RetCodes.RET_RONGCLOUD_UPDATE_GROUP_ERROR);
        }
        return RetResult.success();
    }

    @RestMapping(name = "updateGroupName", auth = true, comment = "修改群组名称")
    public RetResult updateGroupName(UserInfo userInfo, GroupDetail bean) {
        GroupDetail detail = source.find(GroupDetail.class, FilterNode
                .create("groupid", FilterExpress.EQUAL, bean.getGroupid())
                .and("createuserid", FilterExpress.EQUAL, userInfo.getUserid()));
        if (detail != null) {
            source.updateColumn(GroupDetail.class, bean.getGroupid(), "groupname", bean.getGroupname());
        } else {
            return RetCodes.retResult(RetCodes.RET_RONGCLOUD_UPDATE_GROUP_ERROR);
        }
        //下更新在发通知
        {
            GroupNotificationMessage.UpdateGroupDetail updateGroupMsg = new GroupNotificationMessage.UpdateGroupDetail();
            updateGroupMsg.setOperatorNickname(userInfo.getUsername());
            updateGroupMsg.setTargetGroupName(bean.getGroupname());
            // 发布更新群信息消息
            publishGroupNotifyMessage(RongCloudGroupMessage.SUB_MSG_DEFAULT,
                    bean.getGroupid(),
                    userInfo.getUserid(),
                    GroupNotificationMessage.OP_UPDATE,
                    updateGroupMsg,
                    String.format(GroupNotificationMessage.OP_UPDATE_MSG, userInfo.getUsername()));
        }

        return RetResult.success();
    }

    @RestMapping(name = "updateChatBackGround", auth = true, comment = "修改聊天背景")
    public RetResult updateChatBackGround(UserInfo userInfo, UserGroup bean) {
        source.updateColumn(UserGroup.class, bean.getUsergroupid(), "chatbackground", bean.getChatbackground());
        return RetResult.success();
    }

    @Comment("修改聊天背景")
    public RetResult updateChatBackGroundWs(UserGroup bean) {
        source.updateColumn(UserGroup.class, bean.getUsergroupid(), "chatbackground", bean.getChatbackground());
        return RetResult.success();
    }

    @Comment("拉人入群")
    @RestMapping(name = "pullUsersIntoGroup", auth = true, comment = "拉人入群组")
    public RetResult pullUsersIntoGroup(UserInfo userInfo, int[] userIds, GroupDetail bean) {
        List<String> targetUserIds = new ArrayList();
        List<String> targetUserDisplayNames = new ArrayList();
        if (userIds.length == 0) {
            return RetCodes.retResult(RetCodes.RET_GROUP_PULL_USERS_EMPTY);
        }
        if (userIds.length > 0) {
            for (int userId : userIds) {
                UserInfo user = source.find(UserInfo.class, userId);
                join(user, bean);
                targetUserIds.add(Integer.toString(userId, 36));
                targetUserDisplayNames.add(user.getUsername());
            }
        }

        //更新群人数
        refreshGroupUserNum(bean.getGroupid());

        GroupNotificationMessage.AddMemberToGroup addMemberToGroupMsg = new GroupNotificationMessage.AddMemberToGroup();
        // 添加群成员通知
        addMemberToGroupMsg.setOperatorNickname(userInfo.getUsername());
        addMemberToGroupMsg.setTargetUserDisplayNames(targetUserDisplayNames);
        addMemberToGroupMsg.setTargetUserIds(targetUserIds);
        publishGroupNotifyMessage(RongCloudGroupMessage.SUB_MSG_DEFAULT, bean.getGroupid(), userInfo.getUserid(),
                GroupNotificationMessage.OP_ADD_MEMBER, addMemberToGroupMsg,
                String.format(GroupNotificationMessage.OP_ADD_MEMBER_MSG, String.join(";", targetUserDisplayNames)));

        return RetResult.success();
    }

    @Comment("拉人入群")
    public RetResult pullUsersIntoGroupWs(int[] userIds, GroupDetail bean) {
        if (userIds.length == 0) {
            return RetCodes.retResult(RetCodes.RET_GROUP_PULL_USERS_EMPTY);
        }
        if (userIds.length > 0) {
            for (int userId : userIds) {
                UserInfo user = source.find(UserInfo.class, userId);
                joinWs(user.getUserid(), user.getUsername(), bean);
            }
        }
        //更新群人数
        refreshGroupUserNum(bean.getGroupid());
        return RetResult.success();
    }

    @RestMapping(name = "joinGroup", auth = true, comment = "加入群组")
    public RetResult joinGroup(UserInfo userInfo, GroupDetail bean) {
        RetResult result = join(userInfo, bean);
        //先加入群再发通知
        if (result.isSuccess()) {
            //更新群人数
            refreshGroupUserNum(bean.getGroupid());
            GroupNotificationMessage.AddMemberToGroup addMemberToGroupMsg = new GroupNotificationMessage.AddMemberToGroup();
            // 添加群成员通知
            // 添加群成员通知
            addMemberToGroupMsg.setOperatorNickname(userInfo.getUsername());
            addMemberToGroupMsg.setTargetUserDisplayNames(Arrays.asList(userInfo.getUsername()));
            addMemberToGroupMsg.setTargetUserIds(Arrays.asList(Integer.toString(userInfo.getUserid(), 36)));
            publishGroupNotifyMessage(RongCloudGroupMessage.SUB_MSG_DEFAULT,
                    bean.getGroupid(),
                    userInfo.getUserid(),
                    GroupNotificationMessage.OP_ADD_MEMBER,
                    addMemberToGroupMsg, String.format(GroupNotificationMessage.OP_ADD_MEMBER_MSG, userInfo.getUsername()));
        }
        return result;
    }

    @Comment("加入群相关逻辑")
    public RetResult joinWs(int userId, String userName, GroupDetail bean) {
        String userGroupid = bean.getGroupid() + "-" + userId;
        UserGroup userGroup = source.find(UserGroup.class, userGroupid);
        //已经加入群了不能再次加入
        if (userGroup != null) {
            return RetCodes.retResult(RetCodes.RET_GROUP_JOIN_FAILED_MEMBER_OF_GROUP);
        }
        userGroup = new UserGroup();
        userGroup.setUsergroupid(userGroupid);
        userGroup.setGroupid(bean.getGroupid());
        userGroup.setUserid(userId);
        userGroup.setUsername(userName);
        userGroup.setJointime(System.currentTimeMillis());
        source.insert(userGroup);
        return RetResult.success();
    }

    @Comment("加入群相关逻辑")
    private RetResult join(UserInfo userInfo, GroupDetail bean) {
        int userId = userInfo.getUserid();
        String userGroupid = bean.getGroupid() + "-" + userId;
        UserGroup userGroup = source.find(UserGroup.class, userGroupid);
        //已经加入群了不能再次加入
        if (userGroup != null) {
            return RetCodes.retResult(RetCodes.RET_GROUP_JOIN_FAILED_MEMBER_OF_GROUP);
        }
        RetResult joinGroup = rongCloudService.joinGroup(userId, bean.getGroupid(), bean.getGroupname());
        if (joinGroup.isSuccess()) {
            userGroup = new UserGroup();
            userGroup.setUsergroupid(userGroupid);
            userGroup.setGroupid(bean.getGroupid());
            userGroup.setUserid(userId);
            userGroup.setUsername(userInfo.getUsername());
            userGroup.setUsernickname(userInfo.getUsername());
            userGroup.setJointime(System.currentTimeMillis());
            source.insert(userGroup);
        }
        return RetResult.success();
    }

    @RestMapping(name = "updateUserGroupName", auth = true, comment = "更新用户群昵称")
    public RetResult updateUserGroupName(UserInfo userInfo, UserGroup userGroup) {
        int groupId = userGroup.getGroupid();
        int userId = userGroup.getUserid();
        if (userId != userInfo.getUserid()) {
            GroupDetail groupDetail = source.find(GroupDetail.class, groupId);
            if (groupDetail == null) {
                return RetCodes.retResult(RetCodes.RET_GROUP_UNEXIST);
            }
            if (userInfo.getUserid() != groupDetail.getCreateuserid()) {
                return RetCodes.retResult(RetCodes.RET_RONGCLOUD_UPDATENICKNAME_INVALID_PERMISSION);
            }
        }
        userGroup.setUsergroupid(groupId + "-" + userId);
        userGroup.setUsername(userGroup.getUsername());
        userGroup.setUsernickname(userGroup.getUsername());
        source.updateColumn(userGroup, "username");
        return RetResult.success();
    }

    @Comment("更新用户群昵称")
    public RetResult updateUserGroupNameWs(int currentUserId, UserGroup userGroup) {
        int groupId = userGroup.getGroupid();
        int userId = userGroup.getUserid();
        if (userId != currentUserId) {
            GroupDetail groupDetail = source.find(GroupDetail.class, groupId);
            if (groupDetail == null) {
                return RetCodes.retResult(RetCodes.RET_GROUP_UNEXIST);
            }
            if (currentUserId != groupDetail.getCreateuserid()) {
                return RetCodes.retResult(RetCodes.RET_RONGCLOUD_UPDATENICKNAME_INVALID_PERMISSION);
            }
        }
        userGroup.setUsergroupid(groupId + "-" + userId);
        userGroup.setUsername(userGroup.getUsername());
        userGroup.setUsernickname(userGroup.getUsernickname());
        source.updateColumn(userGroup, "username");
        return RetResult.success();
    }

    @Comment("主动退出群组")
    public RetResult quitGroupWs(int userId, int groupId, int newCreatorId) {
        String userGroupId = groupId + "-" + userId;
        //先发通知在退出群
        QuitGroup quitGroupMsg = new QuitGroup();
        GroupDetail groupDetail = source.find(GroupDetail.class, groupId);
        int createuserid = groupDetail.getCreateuserid();
        boolean isManage = createuserid == userId;
        // 群主退群
        UserGroup creatorGroup = null;
        if (isManage) {
            String usergroupid = groupId + "-" + newCreatorId;
            creatorGroup = source.find(UserGroup.class, usergroupid);
            // 管理员用户不存在
            if (creatorGroup == null) {
                return RetCodes.retResult(RetCodes.RET_CREATOR_USER_NOTEXIT_FIRIND);
            }
            if (newCreatorId == userId) {
                return RetCodes.retResult(RetCodes.RET_UPDATE_CREATOR_FIRIND);
            }
            quitGroupMsg.setNewCreatorId(Integer.toString(newCreatorId, 36));
            groupDetail.setCreateuserid(newCreatorId);
            source.update(groupDetail);// 更新群主信息
        }
        source.delete(UserGroup.class, userGroupId);
        //更新群人数
        refreshGroupUserNum(groupId);
        return RetResult.success();
    }

    @RestMapping(name = "quitGroup", auth = true, comment = "主动退出群组")
    public RetResult quitGroup(UserInfo userInfo, int groupId, String groupName, int newCreatorId) {
        String userGroupId = groupId + "-" + userInfo.getUserid();
        //先发通知在退出群
        QuitGroup quitGroupMsg = new QuitGroup();
        GroupDetail groupDetail = source.find(GroupDetail.class, groupId);
        int createuserid = groupDetail.getCreateuserid();
        boolean isManage = createuserid == userInfo.getUserid();
        // 群主退群
        UserGroup creatorGroup = null;
        if (isManage) {
            String usergroupid = groupId + "-" + newCreatorId;
            creatorGroup = source.find(UserGroup.class, usergroupid);
            // 管理员用户不存在
            if (creatorGroup == null) {
                return RetCodes.retResult(RetCodes.RET_CREATOR_USER_NOTEXIT_FIRIND);
            }
            if (newCreatorId == userInfo.getUserid()) {
                return RetCodes.retResult(RetCodes.RET_UPDATE_CREATOR_FIRIND);
            }
            quitGroupMsg.setNewCreatorId(Integer.toString(newCreatorId, 36));
            groupDetail.setCreateuserid(newCreatorId);
            source.update(groupDetail);// 更新群主信息
        }
        quitGroupMsg.setOperatorNickname(userInfo.getUsername());
        List<String> displayNames = new ArrayList<>();
        List<String> targetUserIds = new ArrayList<>();
        targetUserIds.add(Integer.toString(userInfo.getUserid(), 36));
        displayNames.add(userInfo.getUsername());
        quitGroupMsg.setTargetUserDisplayNames(displayNames);
        quitGroupMsg.setTargetUserIds(targetUserIds);
        quitGroupMsg.setOperatorNickname(userInfo.getUsername());
        // 添加群成员通知
        publishGroupNotifyMessage(RongCloudGroupMessage.SUB_MSG_DEFAULT,
                groupId,
                userInfo.getUserid(),
                GroupNotificationMessage.OP_QUIT,
                quitGroupMsg, String.format(GroupNotificationMessage.OP_QUIT_MSG, userInfo.getUsername()));

        RetResult quitGroup = rongCloudService.quitGroup(userInfo.getUserid(), groupId, groupName);
        if (quitGroup.isSuccess()) {
            source.delete(UserGroup.class, userGroupId);
            //更新群人数
            refreshGroupUserNum(groupId);
        }
        return quitGroup;
    }

    @RestMapping(name = "kickUserFromGroup", auth = true, comment = "踢除群组")
    public RetResult kickUserFromGroup(UserInfo userInfo, int[] userIds, int groupId, String groupName) {
        GroupDetail groupDetail = source.find(GroupDetail.class, groupId);
        RetResult result = null;
        // 群不存在
        if (groupDetail == null) {
            return RetCodes.retResult(RetCodes.RET_GROUP_UNEXIST);
        }
        int createuserid = groupDetail.getCreateuserid();
        // 非群主无踢人权限
        if (createuserid != userInfo.getUserid()) {
            return RetCodes.retResult(RetCodes.RET_GROUP_INVALID_PERMISSION);
        }
        // 剔除用户信息
        for (int index = 0; index < userIds.length; index++) {
            int kickUserId = userIds[index];
            if (createuserid == kickUserId) {
                return RetCodes.retResult(RetCodes.RET_GROUP_KICK_MEMBER_IS_GROUP_OWNER);
            }
            UserInfo kickUser = source.find(UserInfo.class, kickUserId);
            if (kickUser == null) {
                return RetCodes.retResult(RetCodes.RET_USER_NOTEXIT_FIRIND);
            }
            String userGroupId = groupId + "-" + kickUserId;
            result = rongCloudService.quitGroup(kickUserId, groupId, groupName);
            if (result.isSuccess()) {
                source.delete(UserGroup.class, userGroupId);
                KickedGroup kickGroupMsg = new KickedGroup();
                List<String> targetUserIds = new ArrayList<>();
                List<String> targetUserDisplayNames = new ArrayList<>();
                targetUserDisplayNames.add(kickUser.getUsername());
                targetUserIds.add(Integer.toString(kickUserId, 36));
                kickGroupMsg.setOperatorNickname(userInfo.getUsername());
                kickGroupMsg.setTargetUserIds(targetUserIds);
                kickGroupMsg.setTargetUserDisplayNames(targetUserDisplayNames);
                // 添加群成员通知
                publishGroupNotifyMessage(
                        RongCloudGroupMessage.SUB_MSG_DEFAULT,
                        groupId,
                        userInfo.getUserid(),
                        GroupNotificationMessage.OP_KICK_MEMBER,
                        kickGroupMsg, String.format(GroupNotificationMessage.OP_KICK_MEMBER_MSG, kickUser.getUsername()));
            }
        }
        //更新群人数
        refreshGroupUserNum(groupId);
        return result;
    }

    @Comment("踢人出群")
    public RetResult kickUserFromGroupWs(int currentUser, int[] userIds, int groupId) {
        GroupDetail groupDetail = source.find(GroupDetail.class, groupId);
        RetResult result = null;
        // 群不存在
        if (groupDetail == null) {
            return RetCodes.retResult(RetCodes.RET_GROUP_UNEXIST);
        }
        int createuserid = groupDetail.getCreateuserid();
        // 非群主无踢人权限
        if (createuserid != currentUser) {
            return RetCodes.retResult(RetCodes.RET_GROUP_INVALID_PERMISSION);
        }
        // 剔除用户信息
        for (int index = 0; index < userIds.length; index++) {
            int kickUserId = userIds[index];
            if (createuserid == kickUserId) {
                return RetCodes.retResult(RetCodes.RET_GROUP_KICK_MEMBER_IS_GROUP_OWNER);
            }
            UserInfo kickUser = source.find(UserInfo.class, kickUserId);
            if (kickUser == null) {
                return RetCodes.retResult(RetCodes.RET_USER_NOTEXIT_FIRIND);
            }
            String userGroupId = groupId + "-" + kickUserId;
            source.delete(UserGroup.class, userGroupId);
        }
        //更新群人数
        refreshGroupUserNum(groupId);
        return result;
    }

    @RestMapping(name = "dismissGroupMsg", auth = true, comment = "解散群")
    public RetResult dismissGroupMsg(UserInfo userInfo, int groupId) {
        int userId = userInfo.getUserid();
        // 先发通知在解散群
        GroupDetail groupDetail = source.find(GroupDetail.class, FilterNode.create("groupid", FilterExpress.EQUAL, groupId).and("createuserid", FilterExpress.EQUAL, userId));
        if (groupDetail == null) {
            return RetCodes.retResult(RetCodes.RET_RONGCLOUD_DIMISS_GROUP_INVALID_PERMISSION);
        }
        DissMissGroup dissMissGroupMsg = new DissMissGroup();
        dissMissGroupMsg.setOperatorNickname(userInfo.getUsername());
        dissMissGroupMsg.setCreator(userId);
        // 解散群通知
        publishGroupNotifyMessage(
                RongCloudGroupMessage.SUB_MSG_DEFAULT,
                groupId,
                userInfo.getUserid(),
                GroupNotificationMessage.OP_DISSMISS,
                dissMissGroupMsg, String.format(GroupNotificationMessage.OP_DISSMISS_MSG, userInfo.getUsername()));
//        RetResult dismissGroup = rongCloudService.dismissGroup(userId, groupId);
//        if (!dismissGroup.isSuccess()) {
//            return dismissGroup;
//        }
//        source.delete(UserGroup.class, FilterNode.create("groupid", FilterExpress.EQUAL, groupId)); // 清除群记录
//        source.delete(GroupDetail.class, groupId); // 删除群信息
        return RetResult.success();
    }

    @Comment("解散群")
    public RetResult dismissGroupWs(int currentUserId, int groupId) {
        GroupDetail group = source.find(GroupDetail.class, FilterNode.create("groupid", FilterExpress.EQUAL, groupId)
                .and("createuserid", FilterExpress.EQUAL, currentUserId));
        if (group != null) {
            source.delete(UserGroup.class, FilterNode.create("groupid", FilterExpress.EQUAL, groupId)); // 清除群记录
            source.delete(GroupDetail.class, groupId); // 删除群信息
        } else {
            return RetCodes.retResult(RetCodes.RET_GROUP_DISMISS_FAILED);
        }
        return RetResult.success();
    }

    @RestMapping(name = "dismissGroup", auth = true, comment = "解散群")
    public RetResult dismissGroup(UserInfo userInfo, int groupId) {
        int userId = userInfo.getUserid();
//        // 先发通知在解散群
//        DissMissGroup dissMissGroupMsg = new DissMissGroup();
//        dissMissGroupMsg.setOperatorNickname(userInfo.getUsername());
//        // 解散群通知
//        publishGroupNotifyMessage(
//                RongCloudGroupMessage.SUB_MSG_DEFAULT,
//                groupId,
//                userInfo.getUserid(),
//                GroupNotificationMessage.OP_DISSMISS,
//                dissMissGroupMsg, String.format(GroupNotificationMessage.OP_DISSMISS_MSG, userInfo.getUsername()));
        RetResult dismissGroup = rongCloudService.dismissGroup(userId, groupId);
        if (!dismissGroup.isSuccess()) {
            return dismissGroup;
        }
        source.delete(UserGroup.class, FilterNode.create("groupid", FilterExpress.EQUAL, groupId)); // 清除群记录
        source.delete(GroupDetail.class, groupId); // 删除群信息
        return RetResult.success();
    }

    @RestMapping(name = "queryGroupList", auth = true, comment = "查询群列表")
    public RetResult queryGroupList(UserInfo userInfo) {
        // 查询当前用户所在的所以群
        List<GroupDetail> queryList = null;
        Sheet<UserGroup> sheet = source.querySheet(UserGroup.class, null, FilterNode.create("userid", FilterExpress.EQUAL, userInfo.getUserid()));
        Collection<UserGroup> rows = sheet.getRows();
        if (rows != null && rows.size() > 0) {
            List<Integer> groupids = rows.stream().map(o -> o.getGroupid()).collect(Collectors.toList());
            GroupDetailBean bean = new GroupDetailBean();
            bean.setGroupid(groupids.stream().toArray(Integer[]::new));
            queryList = source.queryList(GroupDetail.class, bean);
            queryList.forEach(obj -> {
                obj.setCreator(source.find(UserInfo.class, obj.getCreateuserid()));
            });
        }
        return RetResult.success(queryList);
    }

//    @RestMapping(name = "queryGroupMember", auth = true, comment = "查询群组成员")
//    public RetResult queryGroupMember(int groupId) {
//        Sheet<UserGroup> querySheet = source.querySheet(UserGroup.class, null, FilterNode.create("groupid", FilterExpress.EQUAL, groupId));
//        GroupDetail groupDetail = source.find(GroupDetail.class, groupId);
//        Collection<UserGroup> userGroups = null;
//        if ((userGroups = querySheet.getRows()) != null && userGroups.size() > 0) {
//            userGroups.forEach(obj -> {
//                obj.setUserInfo(source.find(UserInfo.class, obj.getUserid()));
//            });
//        }
//        Map<String, Object> resultMap = new HashMap();
//        resultMap.put("groupDetail", groupDetail);
//        resultMap.put("userGroups", userGroups);
//        return RetResult.success(resultMap);
//    }

    @RestMapping(name = "pubGroupMessage", auth = false, comment = "发群消息")
    public RetResult pubGroupMessage(UserInfo userInfo, RongCloudGroupMessage bean) {
        bean.setType(RongCloudMessage.GROUP);
        rongCloudService.pubMessage(bean);
        return RetResult.success();
    }

    @RestMapping(name = "refreshGroup", auth = true, comment = "刷新群组信息")
    public RetResult refreshGroup(int groupId, String groupName) {
        return rongCloudService.refreshGroup(groupId, groupName);
    }

    @RestMapping(name = "syncGroup", auth = true, comment = "同步群组成员")
    public RetResult syncGroup(UserInfo userInfo, HashMap<String, String> groupMap) {
        return rongCloudService.syncGroup(userInfo.getUserid(), groupMap);
    }

    /**
     * 更新群人数
     *
     * @param groupId
     */
    private void refreshGroupUserNum(int groupId) {
        Number numberResult = source.getNumberResult(UserGroup.class, FilterFunc.COUNT, "groupid", FilterNode.create("groupid", FilterExpress.EQUAL, groupId));
        int intValue = numberResult.intValue();
        GroupDetail groupDetail = source.find(GroupDetail.class, groupId);
        // 更新群人数
        if (groupDetail != null) {
            groupDetail.setUsernum(intValue);
            source.update(groupDetail);
        }
    }

    public static void main(String[] args) throws Exception {
        GroupService service = Application.singleton(GroupService.class);
        UserGroup group = new UserGroup();
        group.setGroupid(1000007);
        group.setFace("xxx");
        group.setUsername("xxx");
        group.setUsernickname("www");
        UserGroupHis his = group.createTableHis(System.currentTimeMillis());
        service.source.insert(his);
        System.out.println(his);
//        service.refreshGroupUserNum(100000001);
//        service.
//        int userId = 300000005, joinUserId = 300000012;
//        UserInfo userInfo = new UserInfo();
//        userInfo.setUserid(userId);
//        userInfo.setUsername("创建人");
//        UserInfo joiner = new UserInfo();
//        joiner.setUserid(joinUserId);
//        joiner.setUsername("加入人");
//        GroupDetail bean = new GroupDetail();
//        bean.setGroupname("testGroup002");
//        RetResult createGroup = service.createGroup(userInfo, bean, new int[]{300000001,
//            300000002,
//            300000003,
//            300000004,
//            300000006,
//            300000007,
//            300000008,
//            300000009,
//            300000010,
//            300000011,
//            300000012,
//            300000013,
//            300000014,
//            300000015});
//        GroupDetail detail = (GroupDetail) createGroup.getResult();
//        System.out.println("createGroup =============>>>>" + createGroup.toString());
//        RetResult join = service.joinGroup(joiner, detail);
//        System.out.println("join =============>>>>" + join.toString());
//        RetResult quitGroup = service.quitGroup(userInfo, detail.getGroupid(), groupName);
//        System.out.println("quitGroup=================>>>>" + quitGroup.toString());
//        RetResult kickGroup = service.kickUserFromGroup(joiner.getUserid(), detail.getGroupid(), groupName);
//        System.out.println("kickGroup=================>>>>" + kickGroup.toString());
//        RetResult dismissGroup = service.dismissGroup(userInfo, detail.getGroupid());
//        System.out.println("dismissGroup=================>>>>" + dismissGroup.toString());
//        BasicContent.TextMessage textMessage = new BasicContent.TextMessage("测试文本消息发送！！！");
//        
//        RetResult queryGroup = service.queryGroupMember(detail.getGroupid());
//        
//        System.out.println("queryGroup=====>>>" + queryGroup.toString());
//        
//        RongCloudMessage.RongCloudGroupMessage rongCloudGroupMessage = new RongCloudMessage.RongCloudGroupMessage(detail.getGroupid(),
//                    0,
//                    joiner.getUserid(),
//                    joinUserId, BasicContent.TextMessage.TYPE, textMessage);
//        service.pubGroupMessage(userInfo, rongCloudGroupMessage);
//
//        RetResult queryGroupList = service.queryGroupList(userInfo);
//        System.out.println("queryGroupList=====>>>" + queryGroupList.toString());
//        System.out.println(Integer.toString(100000001, 36));
    }

    /**
     * *************************************消息管理****************************************
     */
    @RestMapping(name = "addgroupGag", comment = "群组成员禁言")
    public RetResult addgroupGag(UserInfo userInfo, int userId, int groupId, int minute) {
        return rongCloudService.addGroupGag(userId, groupId, minute);
    }

    @RestMapping(name = "listGroupGag", comment = "群组成员禁言")
    public RetResult listGroupGaga(UserInfo userInfo, int userId, int groupId, int miunte) {
        return rongCloudService.listGroupGag(groupId);
    }
}
